package com.huluobo.a2203monthdemo.sign

import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2203monthdemo.databinding.ActivitySignBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class SignActivity : BaseActivity<ActivitySignBinding, SignViewModel>() {
    private var signId = 0
    override fun initData() {
        viewModel.signStartSuccess.observe(this) {
            ToastUtils.showLong("签到成功")
            binding.signBtn.text = "签退"
            signId = 1
            SPUtils.getInstance().put(Const.PARAM_SIGN_ID, signId)
        }

        viewModel.signEndSuccess.observe(this) {
            ToastUtils.showLong("签退成功")
            binding.signBtn.text = "签到"
            signId = 0
            SPUtils.getInstance().put(Const.PARAM_SIGN_ID, signId)
        }
    }

    override fun initView() {
        binding.signHeader.headerBack.setOnClickListener { finish() }
        binding.signHeader.headerTitle.text = "签到/签退"

        signId = SPUtils.getInstance().getInt(Const.PARAM_SIGN_ID)
        if (signId == 0) {
            binding.signBtn.text = "签到"
        } else {
            binding.signBtn.text = "签退"
        }

        binding.signBtn.setOnClickListener {
            if (signId == 0) {
                startSign()
            } else {
                endSign()
            }
        }
    }

    private fun endSign() {
        val time = getTime()
        val map = mutableMapOf<String, Any>()
        map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_USER_ID)
        map[Const.PARAM_START_ADDRESS] = "天津市"
        map[Const.PARAM_START_TIME] = time
        map[Const.PARAM_END_ADDRESS] = "天津市"
        map[Const.PARAM_END_TIME] = time
        map[Const.PARAM_SIGN_ID] = signId

        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        viewModel.signEnd(body)
    }

    private fun startSign() {
        val time = getTime()
        val map = mutableMapOf<String, Any>()
        map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_USER_ID)
        map[Const.PARAM_START_ADDRESS] = "天津市"
        map[Const.PARAM_START_TIME] = time
        map[Const.PARAM_END_ADDRESS] = "天津市"
        map[Const.PARAM_END_TIME] = time
        map[Const.PARAM_SIGN_ID] = signId

        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        viewModel.signStart(body)
    }
}